package cn.itcast.bos.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.service.system.UserService;


@SuppressWarnings("all")
/*@Service("bosRealm")   由spring自己来配置bean*/
public class BosRealm  extends AuthorizingRealm{
   @Autowired
   private UserService userService;
   
   
    @Autowired
    private RoleService roleService;
   
  
  @Autowired
   private PermissionService permissionSerivce;
	
    //授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection args) {
		//创建授权信息对象
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//获取认证登录中保存的登录用户user信息
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		//通过用户user id查询到对应的所有角色role对象集合
		List<Role> roles  =  roleService.findByUser(user);
		//把所有的角色对象的关键字添加到授权信息对象中
		for (Role role : roles) {
			simpleAuthorizationInfo.addRole(role.getKeyword());
		}
		//通过用户user id查询到对应的所有权限permissions对象集合
		List<Permission> permissions = permissionSerivce.findByUser(user);
		//把所有的权限对象的关键字添加到授权信息对象中
		for (Permission permission : permissions) {
			System.out.println("权限"+permission.getKeyword());
			 simpleAuthorizationInfo.addStringPermission(permission.getKeyword());
		}
		//返回授权信息对象
		return simpleAuthorizationInfo;
		
	}

	//认证	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("shiro 认证管理... ");
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		System.out.println("用户名是"+usernamePasswordToken.getUsername());
		System.out.println("密码是"+usernamePasswordToken.getPassword());
		User user = userService.findByUsername(usernamePasswordToken.getUsername());
		if(user == null){
			return null;
		}else{
			return new SimpleAuthenticationInfo(user, user.getPassword(),getName());
		}
	}

}
